#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"

if [ -z "$LMD_DATA_ROOT" ]; then
    echo "Error: Env LMD_DATA_ROOT is not defined."
    exit 1
else
    echo "Env LMD_DATA_ROOT: $LMD_DATA_ROOT"
fi

export ENV_INIT_SCRIPT_DIR="${LMD_DATA_ROOT}/scripts/env-init"
export GLOBAL_TOOLS_DIR_WIN="${LMD_DATA_ROOT}\scripts\global-tools"
export MINICONDA_INSTALL_TARGET_DIR_WIN="${GLOBAL_TOOLS_DIR_WIN}\miniconda3"

mkdir -p "$ENV_INIT_SCRIPT_DIR"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/download_utils.sh"

export DEFAULT_MINICONDA_MIRROR_PREFIX="https://repo.anaconda.com/miniconda"
export MINICONDA_MIRROR_PREFIX="$DEFAULT_MINICONDA_MIRROR_PREFIX"
export MINICONDA_MIRROR_PREFIX_SUB="$DEFAULT_MINICONDA_MIRROR_PREFIX"

function init_mirror_host {
    if [ -n "$GITHUB_PROXY" ]; then
        url="https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/win-64/_pytorch_select-1.2.0-gpu.conda"
        NO_REVOKE_PARAM=""
        if current_os_is_windows; then
            NO_REVOKE_PARAM="--ssl-no-revoke"
        fi
        status_code=$(curl $NO_REVOKE_PARAM -o /dev/null -s -w "%{http_code}\n" "$url")
        echo "Detect tsinghua conda mirror: "$status_code
        if [ "$status_code" -eq 200 ]; then
            echo "Access to tsinghua mirror is allowed."
            export MINICONDA_MIRROR_PREFIX="https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda"
        else
            echo "Access to tsinghua mirror is denied. HTTP status code: $status_code. use HIT mirror"
            export MINICONDA_MIRROR_PREFIX="https://mirror.hit.edu.cn/anaconda/miniconda"
        fi

        export MINICONDA_MIRROR_PREFIX_SUB="https://mirror.nju.edu.cn/anaconda/miniconda"
    fi
}

function download_installer {
    local LOCAL_FILE="$1"
    local URL="$2"
    init_mirror_host
    download_with_resume "$LOCAL_FILE" "${MINICONDA_MIRROR_PREFIX}/${URL}"
    exit_code=$?

    if [ $exit_code -ne 0 ]; then
        echo "exit_code: "$exit_code
        download_with_resume "$LOCAL_FILE" "${MINICONDA_MIRROR_PREFIX_SUB}/${URL}"
    fi
    
    exit_code=$?

    if [ $exit_code -ne 0 ]; then
        echo "exit_code: "$exit_code
        download_with_resume "$LOCAL_FILE" "${DEFAULT_MINICONDA_MIRROR_PREFIX}/${URL}"
    fi
}

function install_miniconda {
    echo 'install_miniconda'
    CONDA_VERSION="py313_25.7.0-2"
    
    if [ -f /etc/os-release ]; then
        echo "This is a Linux system."
    elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        echo "This is a macOS system."
        ARCH=$(uname -m)
        # CONDA_INSTALL_SCRIPT_URL=""
        if [ "$ARCH" == "x86_64" ]; then
            echo "Intel-based Mac."
            CONDA_INSTALL_SCRIPT_FILE_NAME=Miniconda3-${CONDA_VERSION}-MacOSX-x86_64.sh
        elif [ "$ARCH" == "arm64" ]; then
            echo "Apple Silicon (M-series) Mac."
            CONDA_INSTALL_SCRIPT_FILE_NAME=Miniconda3-${CONDA_VERSION}-MacOSX-arm64.sh
        fi

        CONDA_INSTALL_SCRIPT="${ENV_INIT_SCRIPT_DIR}/${CONDA_INSTALL_SCRIPT_FILE_NAME}"
        # curl --retry 5 -o $CONDA_INSTALL_SCRIPT $CONDA_INSTALL_SCRIPT_URL
        download_installer "$CONDA_INSTALL_SCRIPT" $CONDA_INSTALL_SCRIPT_FILE_NAME
        echo "download ok."

        if [ -d "$MINICONDA_DIR_IN_HOME" ]; then
            echo "remove miniconda3 old files"
            rm -rf "$MINICONDA_DIR_IN_HOME"
        fi
        chmod +x "$CONDA_INSTALL_SCRIPT"
        bash "$CONDA_INSTALL_SCRIPT" -b -u
    elif current_os_is_windows; then
        echo "This is a Windows system."
        export CONDA_INSTALLER_EXE="Miniconda3-${CONDA_VERSION}-Windows-x86_64.exe"
        export CONDA_INSTALLER_PATH="${ENV_INIT_SCRIPT_DIR}/${CONDA_INSTALLER_EXE}"
        # CONDA_INSTALL_TARGET_DIR="${GLOBAL_TOOLS_DIR}/miniconda3"
        # CONDA_INSTALLER_URL=https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe
        
        echo "start download: "$CONDA_INSTALLER_URL
        download_installer "$CONDA_INSTALLER_PATH" "Miniconda3-${CONDA_VERSION}-Windows-x86_64.exe"
        echo "download ok."

        output=$(cmd //c "$CONDA_INSTALLER_PATH -ArgumentList /S" 2>&1)
        exit_code=$?

        echo "install to home dir exit_code: $exit_code"
        echo "output:"
        echo "$output"
        if [ $exit_code -ne 0 ]; then
            echo "install to home dir exit_code: $exit_code"
            install_to_global_tools
        else
            if echo "$output" | grep -i "::error::" > /dev/null; then
                echo "detected error in output:"
                echo "$output"
                install_to_global_tools
            fi
        fi
        echo "installation done"
    else
        echo "Unknown OS"
    fi
}

function install_to_global_tools {
    echo "install to global-tools dir $MINICONDA_INSTALL_TARGET_DIR_WIN"
    if [ -d "$MINICONDA_INSTALL_TARGET_DIR_WIN" ]; then
        echo "remove dir ${MINICONDA_INSTALL_TARGET_DIR_WIN}"
        rm -rf "$MINICONDA_INSTALL_TARGET_DIR_WIN"
    fi
    API_URL="http://localhost:19312/api/self-manage/globa-tools/install-miniconda?installer=${CONDA_INSTALLER_EXE}"
    curl -v --ssl-no-revoke -s "$API_URL"
    exit_code=$?
    echo "install to global-tools dir done. $exit_code"
}

function check_miniconda {
    MINICONDA_DIR_IN_HOME="${HOME}/miniconda3"
    if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        # macOS
        CONDA_BIN_PATH=$(command -v "$MINICONDA_DIR_IN_HOME/bin/conda")
        MINICONDA_ACTIVE_BIN_PATH="$MINICONDA_DIR_IN_HOME/bin/activate"
    elif current_os_is_windows; then
        # Windows
        # check in the global-tools dir
        CONDA_BIN_PATH=$(command -v "${MINICONDA_INSTALL_TARGET_DIR_WIN}/Scripts/conda")
        if [ -z "$CONDA_BIN_PATH" ]; then
            CONDA_BIN_PATH=$(command -v "${MINICONDA_DIR_IN_HOME}/Scripts/conda")
            MINICONDA_ACTIVE_BIN_PATH="${MINICONDA_DIR_IN_HOME}/Scripts/activate.bat"
            if [ -z "$CONDA_BIN_PATH" ]; then
                MINICONDA_DIR_IN_PROGRAM_DATA="/c/ProgramData/miniconda3"
                CONDA_BIN_PATH=$(command -v "${MINICONDA_DIR_IN_PROGRAM_DATA}/Scripts/conda")
                MINICONDA_ACTIVE_BIN_PATH="${MINICONDA_DIR_IN_PROGRAM_DATA}/Scripts/activate.bat"
            else
                echo "found miniconda in home: $CONDA_BIN_PATH"
            fi
        else
            # CONDA_BIN_PATH="${MINICONDA_INSTALL_TARGET_DIR_WIN}/Scripts/conda"
            MINICONDA_ACTIVE_BIN_PATH="${MINICONDA_INSTALL_TARGET_DIR_WIN}/Scripts/activate.bat"
            echo "Found conda in LMD global-tools: $CONDA_BIN_PATH"
        fi
    fi

    if [ -z "$CONDA_BIN_PATH" ]; then
        install_miniconda
    else
        echo "miniconda $CONDA_BIN_PATH exist. skip install."
    fi

    "$MINICONDA_ACTIVE_BIN_PATH"
    "$CONDA_BIN_PATH" init --all
}

check_miniconda

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"